package com.example.safeassistan.train.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.train.model.DownLoadDetail;
import com.example.safeassistan.train.model.MateralList;
import com.example.safeassistan.train.model.MaterialDetail;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.StringUtils;
import com.example.safeassistan.utile.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static com.example.safeassistan.common.MethodUtils.getUserId;


/***资料云库详情**/
public class ActivityKnowledgeBaseDetail extends BaseActivity implements View.OnClickListener {
    private String path ="/safeassistan/material";
    private String filename = "";
    private MaterialDetail model;


    private  TextView tvTitle,tvIntro,tvCreateTime,tvDownLoad;
     private WebView web_view;

    private String id = "";
    private String suffix = "";
    private MyHandler myHandler;

    public static void actionStart(Context context, String id) {
        Intent intent = new Intent(context, ActivityKnowledgeBaseDetail.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvDownLoad:
                //下载附件
             //   downLoad(model.getResult().getViewUrl());
                break;
        }
    }


    public int DownLoadFileFormUrl(String urlLoadPath, String savaDirPath,String filename){
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        HttpURLConnection httpURLConnection = null;

        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Log.i(TAG," 未安装 SD 卡");
            return  0;
        }
        File pathSd = Environment.getExternalStorageDirectory();  //获取 SD 卡路径
        File fileRealDirectoty  = new File(pathSd.getAbsolutePath() + File.separator + savaDirPath);
        Log.i(TAG,"文件保存的真正目录： " + fileRealDirectoty);
        if (!fileRealDirectoty.exists()) {  //如果目录 不存在 ，就创建
            Log.i(TAG,"创建 存储文件夹");
            fileRealDirectoty.mkdirs();
        }
        //获取要下载的文件名称，在这里可以更改下载的文件名
        String fileName = filename;
        //String fileName = "test.zip";
        //创建 这个文件名 命名的 file 对象
        File file = new File(fileRealDirectoty,fileName);
        Log.i(TAG,"file: " + file);
        if (!file.exists()) {  //倘若没有这个文件
            try {
                Log.i(TAG,"创建文件");
                file.createNewFile();  //创建这个文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            URL url = new URL(urlLoadPath);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            int code = httpURLConnection.getResponseCode();
            if(code == 200) {
                //网络连接成功
                Log.e(TAG,"网络连接成功");
            } else {
                //网络返回异常
                Log.e(TAG,"网络连接异常");
            }
            //根据响应获取文件大小
            int fileSize = httpURLConnection.getContentLength();
            Log.i(TAG,"文件大小： " + fileSize);
            inputStream = httpURLConnection.getInputStream();
            fileOutputStream = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int tem = 0;
            while ((tem = inputStream.read(b))!= -1) {
                fileOutputStream.write(b,0,tem);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return 0;
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }

                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.i(TAG,"文件下载 成功");
        return 1;
    }

    public void downLoad(String url){
        //检查相应权限
        CheckThread checkThread  = new CheckThread();
        checkThread.start();
        try {
            checkThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                //调用下载函数
               if(DownLoadFileFormUrl(url,path,filename)==1) {//下载成功
                   //从消息池中取出一个message
                                 Message msg = myHandler.obtainMessage();
                                 //Bundle是message中的数据
                                 Bundle b = new Bundle();
                                 b.putInt("material", 1);
                                 msg.setData(b);
                                 //传递数据
                                myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
               }

            }
        }).start();
    }

    class MyHandler extends Handler {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            // 这里用于更新UI
              Bundle b = msg.getData();
               if(b.getInt("material",0)==1){
                   //下载成功
                   ToastUtil toastUtil=new ToastUtil(getContext(),R.layout.popu_success,"下载成功",1);
                   toastUtil.show();
               }else {
                   //下载失败
                   ToastUtil toastUtil=new ToastUtil(getContext(),R.layout.popu_success,"下载失败",1);
                   toastUtil.show();
               }
        }
    }

    //sd 卡权限申请
    private void checkPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
        }
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        if(requestCode == 100){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "");
            }
        }
    }

    public  class CheckThread  extends  Thread{
        public void run() {
            checkPermission();
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_materail_detail;
    }

    @Override
    protected void initView() {
        setTitleText("资料详情");
        id = getIntent().getStringExtra("id");
        tvIntro=findViewById(R.id.tvIntro);
        tvTitle=findViewById(R.id.tvTitle);
        tvDownLoad=findViewById(R.id.tvDownLoad);
        web_view = findViewById(R.id.web_view);
        tvCreateTime=findViewById(R.id.tvCreateTime);
        myHandler=new MyHandler();
        tvDownLoad.setOnClickListener(this::onClick);
    }
    //设置数据
    public void setView() {
        tvTitle.setText(model.getResult().getPostTitle());
        tvIntro.setText(model.getResult().getPostSource());
        tvCreateTime.setText(model.getResult().getCreateTime());

//        if (model.getResult().getViewUrl()!=null){
//            tvDownLoad.setVisibility(View.VISIBLE);
//        }else {
//            tvDownLoad.setVisibility(View.GONE);
//        }

        filename = model.getResult().getPostTitle()+suffix;

        StringBuilder sb = new StringBuilder();
        sb.append(getHtmlData(model.getResult().getPostContent()));
        web_view.loadDataWithBaseURL(null,sb.toString(),"text/html", "utf-8", null);
    }

    /**
     * 富文本适配
     */
    private String getHtmlData(String bodyHTML) {
        String head = "<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:auto; height:auto;}</style>"
                + "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }


    //获取资料详情
    public void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("postId", String.valueOf(id));
        new HttpRequest(getContext()).doGet(UrlConstants.taskqueryRepositoryById, "", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), MaterialDetail.class);
                        if (obj instanceof MaterialDetail) {
                            model = (MaterialDetail) obj;
                            setView();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }
}